import { NumberFormat, forMater, getEcharsData96 } from '../../utils';
import { liaoningHeaderMap } from './helper';
import { TIME_24, TIME_96 } from '@/pages/ETrade/components/helper';

// 计算日前结算电价
export const getProvincialDayaheadStatementPrice96 = (data) => {
  const echartsValues = [];
  const provincialDayaheadStatementIncome = [];
  const provincialDayaheadStatementQuantity = [];
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      let income = y.data.provincialDayaheadStatementIncome;
      let quantity = y.data.provincialDayaheadStatementQuantity;
      if (
        provincialDayaheadStatementIncome[index] ||
        provincialDayaheadStatementIncome[index] === 0
      ) {
        provincialDayaheadStatementIncome[index] =
          Number(provincialDayaheadStatementIncome[index]) + Number(income);
      } else {
        provincialDayaheadStatementIncome.push(income);
      }
      if (
        provincialDayaheadStatementQuantity[index] ||
        provincialDayaheadStatementQuantity[index] === 0
      ) {
        provincialDayaheadStatementQuantity[index] =
          Number(provincialDayaheadStatementQuantity[index]) + Number(quantity);
      } else {
        provincialDayaheadStatementQuantity.push(quantity);
      }
    });
  });
  provincialDayaheadStatementIncome.map((item, index) => {
    let result = 0;
    if (provincialDayaheadStatementQuantity[index] != 0) {
      result = item / provincialDayaheadStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算实时结算电价
export const getProvincialRealtimeStatementPrice96 = (data) => {
  const echartsValues = [];
  const provincialRealtimeStatementIncome = [];
  const provincialRealtimeStatementQuantity = [];
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      let income = y.data.provincialRealtimeStatementIncome;
      let quantity = y.data.provincialRealtimeStatementQuantity;
      if (
        provincialRealtimeStatementIncome[index] ||
        provincialRealtimeStatementIncome[index] === 0
      ) {
        provincialRealtimeStatementIncome[index] =
          Number(provincialRealtimeStatementIncome[index]) + Number(income);
      } else {
        provincialRealtimeStatementIncome.push(income);
      }
      if (
        provincialRealtimeStatementQuantity[index] ||
        provincialRealtimeStatementIncome[index] === 0
      ) {
        provincialRealtimeStatementQuantity[index] =
          Number(provincialRealtimeStatementQuantity[index]) + Number(quantity);
      } else {
        provincialRealtimeStatementQuantity.push(quantity);
      }
    });
  });
  provincialRealtimeStatementIncome.map((item, index) => {
    let result = 0;
    if (provincialRealtimeStatementQuantity[index] != 0) {
      result = item / provincialRealtimeStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算过渡电价
export const getTransitionPrice96 = (data, price) => {
  const echartsValues = [];
  const baseQuantity = [];
  const provincialDayaheadClearingQuantity = [];
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      let income = y.data.baseQuantity;
      let quantity = y.data.provincialDayaheadClearingQuantity;
      if (baseQuantity[index] || baseQuantity[index] === 0) {
        baseQuantity[index] = Number(baseQuantity[index]) + Number(income);
      } else {
        baseQuantity.push(income);
      }
      if (
        provincialDayaheadClearingQuantity[index] ||
        provincialDayaheadClearingQuantity[index] === 0
      ) {
        provincialDayaheadClearingQuantity[index] =
          Number(provincialDayaheadClearingQuantity[index]) + Number(quantity);
      } else {
        provincialDayaheadClearingQuantity.push(quantity);
      }
    });
  });
  baseQuantity.map((item, index) => {
    let result = 0;
    if (provincialDayaheadClearingQuantity[index] != 0) {
      result = item / provincialDayaheadClearingQuantity[index];
    }
    const kValue = NumberFormat(result, 100);
    const transitionPrice = kValue * 332 + (1 - kValue) * Number(price[index]);
    echartsValues.push(NumberFormat(transitionPrice, 100));
  });

  return echartsValues;
};

// 计算算术均价
export const _getTotalStatementEnergyPrice = (data, name) => {
  const echartsValues = [];
  const newData = []; // 过滤有综合电价的数据
  let totalStatementEnergyIncome = 0;
  data.map((item) => {
    if (item[name]) {
      newData.push(item);
    }
  });
  newData.map((item) => {
    totalStatementEnergyIncome += Number(item[name]);
  });

  data.map((v) => {
    const result = totalStatementEnergyIncome / newData.length;
    echartsValues.push(NumberFormat(result, 100) ? NumberFormat(result, 100) : '-');
    /* echartsValues.push(
      v?.provincialRealtimeClearingQuantity && v?.provincialRealtimeClearingQuantity !== '0.00'
        ? NumberFormat(result, 100)
        : '-',
    ); */
  });
  return echartsValues;
};

// 计算两数之和相除
export const getPowerForecastPrice = (data, denominatorName, molecularName) => {
  const echartsValues = [];
  const denominatorNameAdd = getEcharsData96(data, denominatorName); // 分母参数之和
  const molecularNameAdd = getEcharsData96(data, molecularName); // 分子参数之和
  denominatorNameAdd.map((item, index) => {
    let result = 0;
    if (molecularNameAdd[index] !== 0) {
      result = item / molecularNameAdd[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};

//子页面处理数据方法选择
export const dealDataChoose = (funcName, ...key) => {
  const map = {
    forMater,
    getEcharsData96,
    _getTotalStatementEnergyPrice,
    getPowerForecastPrice,
    getProvincialDayaheadStatementPrice96,
    getProvincialRealtimeStatementPrice96,
    getTransitionPrice96,
  };
  return map[funcName](...key);
};

export const dealDataMap = (chartMap, chartData, dataMap) => {
  Object.values(chartMap).map((item) => {
    Object.entries(item).map((t) => {
      const _data = t[1].useData === false ? [] : [chartData];
      const _funcName = t[1].funcName;
      const _param = t[1]?.param || [];
      const dependentValue = dataMap?.[t[1]?.dependentValue];

      dataMap[t[0]] = dealDataChoose(_funcName, ..._data, ..._param, dependentValue);
    });
  });
};

const totalDealFunc = (tag, meta, title, value) => {
  let obj = {};
  obj = {
    title,
    tag,
    name: title,
    crumbsName: title,
  };
  meta.forEach((_t, _i) => {
    obj[liaoningHeaderMap[_t]] = value[_i];
    /* if (_i > 1) {
      obj[liaoningHeaderMap[_t]] = _t.includes('电量')
        ? parseFloat(value[_i]).toFixed(3)
        : parseFloat(value[_i]).toFixed(2);
    } else {
      obj[liaoningHeaderMap[_t]] = value[_i];
    } */
  });
  obj.children = [];
  return obj;
};

const dealFunc = (tag, meta, title, value, crumbsName, id, index, pointNum) => {
  let obj = {};
  const _title =
    tag === '时点'
      ? pointNum === '96'
        ? TIME_96[title - 1]
        : TIME_24[title - 1]
      : tag === '日期'
      ? title.replaceAll('-', '')
      : title;
  obj = {
    title: _title,
    tag,
    name: _title,
    crumbsName: crumbsName ? crumbsName + '__' + _title : _title,
    id: id ? id + '-' + index : index + 1,
  };
  meta.forEach((_t, _i) => {
    obj[liaoningHeaderMap[_t]] = value[_i];
    /* if (_i > 1) {
      obj[liaoningHeaderMap[_t]] = _t.includes('电量')
        ? parseFloat(value[_i]).toFixed(3)
        : parseFloat(value[_i]).toFixed(2);
    } else {
      obj[liaoningHeaderMap[_t]] = value[_i];
    } */
  });

  return obj;
};

export const getNewFlagDataSource = (dataSource, order, pointNum) => {
  if (!dataSource?.size) return [];
  const formatForTable = (item, optionName, crumbsName = '', id = '', index = 0) => {
    const arr = [];
    Object.entries(item).map((t, i) => {
      if (t[0] === 'total') {
        return;
      }
      //最后一个维度为数组
      if (t[1] instanceof Array) {
        arr.push(
          dealFunc(optionName[index], dataSource.head, t[0], t[1], crumbsName, id, i, pointNum),
        );
        return;
      }
      const obj = dealFunc(
        optionName[index],
        dataSource.head,
        t[0],
        t[1]['total'],
        crumbsName,
        id,
        i,
        pointNum,
      );
      obj.children = formatForTable(t[1], optionName, obj.crumbsName, obj.id, index + 1);
      arr.push(obj);
    });
    arr.sort((a, b) => {
      if (optionName[index] === '交易单元') {
        return a.title.localeCompare(b.title, 'zh-CN');
      }
      //默认时点排序方式
      return a.title > b.title ? 1 : -1;
    });
    return arr;
  };
  // 添加合计行
  return [
    totalDealFunc(order[0], dataSource.head, '合计', dataSource.data['total']),
    ...formatForTable(dataSource.data, order),
  ];
};

// 根据名称拿指定数据
export const newForMater = (data, name) => {
  const newValue = [];
  data.map((item) => {
    if (item) {
      newValue.push(item[name] === null ? '' : item[name]);
    } else {
      newValue.push('');
    }
  });
  return newValue;
};

export const getXaxis = (data, name) => {
  const newValue = [];
  data?.map((item) => {
    newValue.push(item[name]);
  });
  return newValue;
};

//表格选中图表数据
export const chooseData = (data, value) => {
  const { name, flag = '', date = '' } = value;
  let isSDN = false; // 判断是否是场站-日期-96/24点数据
  let echarsData = [];
  let XAXIS;
  if (value?.children?.length !== 0) {
    echarsData = value?.children || [];
    XAXIS = getXaxis(value?.children || [], 'name');
  }
  return {
    echarsData,
    XAXIS,
    isSDN,
  };
};

// 格式化导出数据
export const formatJson = (filterVal, jsonData) => {
  return jsonData.map((v) => {
    return filterVal.map((j) => {
      return v[j] ?? '-';
    });
  });
};

// 处理排序数据
export const removeEmptyRowData = (dataSource, name) => {
  const sortData = [];
  const noSortData = [];

  dataSource.map((item) => {
    if (item[name] || item[name] == 0) {
      sortData.push(item);
    } else {
      noSortData.push(item);
    }
  });
  return {
    noSortData,
    sortData,
  };
};
